package si.yun.web;

import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import si.yun.entity.R;
import si.yun.service.WechatPayService;
import si.yun.service.impl.WechatServiceImpl;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;

@Controller
@RequestMapping("/wechat")
public class WechatController {
	@Autowired
	private WechatPayService wechatPayService;

	private final Logger logger = LoggerFactory.getLogger(WechatServiceImpl.class);
	/**
	 * 统一下单接口
	 */
	@RequestMapping(value="/wechatAppPay")
	@ResponseBody
	public R unifiedOrder(@RequestParam Map<String, Object> map,HttpServletRequest request) {
		try {
			// 2、开始微信支付统一下单
			R resultMap = wechatPayService.unifiedOrder(map,request);
			return resultMap;//系统通用的返回结果集，见文章末尾
		} catch (Exception e) {
			return R.error("微信调取异常");
		}
	}
	/**
	 * @Description  退款接口
	 * @return si.yun.entity.R
	 * @Date 2021/12/20 15:41
	 **/
	@RequestMapping(value="/refund")
	@ResponseBody
	public R refund(@ApiParam(value = "订单号") @RequestParam String orderNo,
							@ApiParam(value = "退款金额") @RequestParam double amount,
							@ApiParam(value = "退款原因") @RequestParam(required = false) String refundReason){

		return wechatPayService.refund(orderNo, amount, refundReason);
	}

	/**
	 * 微信支付异步通知
	 */
	@RequestMapping(value = "/notify")
	@ResponseBody
	public String payNotify(HttpServletRequest request) {
		InputStream is = null;
		String xmlBack = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[报文为空]]></return_msg></xml> ";
		try {
			is = request.getInputStream();
			// 将InputStream转换成String
			BufferedReader reader = new BufferedReader(new InputStreamReader(is));
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			xmlBack = wechatPayService.notify(sb.toString());
		} catch (Exception e) {
			logger.error("微信手机支付回调通知失败：", e);
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return xmlBack;
	}
}
